package io.youngking.modules.weixin.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.youngking.modules.wxuserinfo.entity.WxuserinfoEntity;
import io.youngking.modules.wxuserinfo.service.WxuserinfoService;
import io.youngking.weixin4j.Weixin;
import io.youngking.weixin4j.WeixinException;
import io.youngking.weixin4j.util.MD5;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static io.youngking.weixin4j.util.MD5.encryptByMd5;

/**
 * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
 * 获取code后，请求以下链接获取access_token：
 */
@Controller
@RequestMapping("/callBackController")
public class CallBackController {
    @Autowired
    private WxuserinfoService wxuserinfoService;

    @RequestMapping("/callBack")
    public String callBack(HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException, WeixinException {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        Weixin weixin=new Weixin();
        try{
            String openid = weixin.sns().getOpenId(code);
            EntityWrapper ew = new EntityWrapper();
            ew.setEntity(new WxuserinfoEntity());
            ew.where("openid = {0}",openid);
            WxuserinfoEntity wxuserinfo = wxuserinfoService.selectOne(ew);
            if(wxuserinfo!=null){
                String wxuserinfoid = wxuserinfo.getId().toString();
                return "redirect:http://www.yanzuohotel.com/"+state+"?wxuserinfoid="+wxuserinfoid;
            }else {
                return "redirect:http://www.yanzuohotel.com/error";
            }
        }catch (Exception E){
            return E.getMessage();
        }
    }
}
